//
//  UseLineVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/24.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "UseLineVC.h"
#import "TopBackView.h"
#import "LineViewCell.h"
 
#import "RootViewController.h"

#import "AddUserLineVC.h"
#import "NullView.h"

@interface UseLineVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NullView *nullView;

@end

@implementation UseLineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = [NSMutableArray array];
    
    TopBackView *topBackView= [[TopBackView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"意向方向"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    self.view.backgroundColor = GrayColor;
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 60 * kHeight) andTitle:@"" andImage:[UIImage imageNamed:@"no_lines"]];
    self.nullView.backgroundColor = GrayColor;
    

    [self initDataSource];
    
    [self initVSubViews];

}

-(void)initDataSource
{
    
    self.nullView.label.text = @"暂无线路";
    
    [Common requestWithUrlString:often_line contentType:application_json errorShow:YES finished:^(id responseObj) {
        
        if (self.dataArray.count > 0) {
            [self.dataArray removeAllObjects];
        }
        
        if ([responseObj[@"data"] count] > 0) {
            
            for (NSDictionary *dic in responseObj[@"data"]) {
                
                [self.dataArray addObject:dic];
            }
            
            
            [self.nullView removeFromSuperview];
            
        } else {
            
            [self.tableView addSubview:self.nullView];
            
        }
        
        [self.tableView reloadData];
        
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)initVSubViews
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64 - Button_height - 30) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = GrayColor;
    
    [self.view addSubview:self.tableView];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(18, CGRectGetMaxY(self.tableView.frame) + 10, screenWidth - 36, Button_height);
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [addButton setTitle:@"新增线路" forState:UIControlStateNormal];
    [addButton setBackgroundColor:YellowColor];
    [addButton addTarget:self action:@selector(addLines) forControlEvents:UIControlEventTouchUpInside];
    addButton.layer.cornerRadius = 5;
    [self.view addSubview:addButton];
}

//添加路线
-(void)addLines
{
//    LineKeepViewController *lineVC = [[LineKeepViewController alloc]init];
//    [self.navigationController pushViewController:lineVC animated:YES];
//
    
    AddUserLineVC * lineVC = [[AddUserLineVC alloc]init];
    [self.navigationController pushViewController:lineVC animated:YES];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *string = @"CenterCell";
    LineViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[LineViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:string];
    }
    
    if (self.dataArray.count > 0) {
        
//
         cell.startL.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"departProvinceName"]];
        
         cell.endL.text = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.section][@"receiptProvinceName"]];
        
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.deleteButton addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.tag = indexPath.section + 400;
    
    
    [cell.editButton addTarget:self action:@selector(editRow:) forControlEvents:UIControlEventTouchUpInside];
    cell.editButton.tag = indexPath.section + 1000;
    
    
    return cell;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//删除
-(void)deleteRow:(UIButton *)sender
{
    NSString *idString = self.dataArray[sender.tag - 400][@"id"];
    
    [self.tableView beginUpdates];
    
    NSString *urlString = [NSString stringWithFormat:@"%@addr/del",Main_interface];
  
    [[Common shared] afPostRequestWithUrlString:urlString parms:@{@"id":idString} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dic[@"success"] boolValue]) {
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            //        dicionary[@"message"] 提示删除是否成功
            
#warning 可以添加提示框
            [self.dataArray removeObjectAtIndex:sender.tag - 400];
            
//            NSIndexPath *deletePath = [NSIndexPath indexPathForRow:0 inSection:sender.tag - 400];
            
            //删除一行
//            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:deletePath] withRowAnimation:UITableViewRowAnimationLeft];
            
            //删除一个section
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sender.tag - 400] withRowAnimation:UITableViewRowAnimationLeft];
            [self.tableView endUpdates];
            
            [self initDataSource];
        }
    
    } failedBlock:^(NSString *errorMsg) {
        
    }];
    
}
//编辑
-(void)editRow:(UIButton *)sender
{

    AddUserLineVC * lineVC = [[AddUserLineVC alloc]init];
        
    lineVC.orderId = self.dataArray[sender.tag - 1000][@"id"];
    lineVC.startCityName = self.dataArray[sender.tag - 1000][@"departProvinceName"];
    lineVC.startCityCode = self.dataArray[sender.tag - 1000][@"departProvinceCode"];
    lineVC.endCityName = self.dataArray[sender.tag - 1000][@"receiptProvinceName"];
    lineVC.endCityCode = self.dataArray[sender.tag - 1000][@"receiptProvinceCode"];
    
    [self.navigationController pushViewController:lineVC animated:YES];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
    [self initDataSource];
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
